let REMOTE_PLUGINS = []
let INSTALLED_PLUGINS = []

let REMOTE_PLUGINS_MAP = {}

self.addEventListener('message', (e) => {
  switch (e.data.event) {
    case 'auto-upgrade':
      // console.log('>>>> auto-upgrade: ', e)
      break
    case 'set-installed-plugins':
      INSTALLED_PLUGINS = e.data.data.list || INSTALLED_PLUGINS
      // console.log('INSTALLED_PLUGINS: ', INSTALLED_PLUGINS)
      _run()
      break
    case 'set-all-plugins':
      REMOTE_PLUGINS = e.data.data.list || REMOTE_PLUGINS
      REMOTE_PLUGINS_MAP = REMOTE_PLUGINS.reduce((prev, curr) => {
        prev[curr.pid] = {
          version: curr.version,
          data: curr
        }
        return prev
      }, {})
      // console.log('REMOTE_PLUGINS_MAP: ', REMOTE_PLUGINS_MAP)
      _run()
      break
    default:
      break
  }
})

function _run () {
  if (INSTALLED_PLUGINS.length < 1 || REMOTE_PLUGINS.length < 1) return
  INSTALLED_PLUGINS.forEach(_runItem)
}

function _runItem (item) {
  if (!REMOTE_PLUGINS_MAP.hasOwnProperty(item.pid)) return
  let _compareRes = _compareVersion(item.version, REMOTE_PLUGINS_MAP[item.pid].version)
  if (_compareRes == -1) {
    // 需要更新
    self.postMessage({
      event: 'upgrade-plugin',
      data: REMOTE_PLUGINS_MAP[item.pid].data
    })
  }
}

/**
 * 比较版本号, 3段式版本号： X.X.X
 * @param {*} newVersion 
 * @param {*} oldVersion 
 * 
 * @return -1, 0, 1
 *    -1: newVersion < oldVersion
 *     0: newVersion == oldVersion
 *     1: newVersion > oldVersion
 */
export function _compareVersion (newVersion, oldVersion) {
  if (newVersion === oldVersion) return 0
  if (!newVersion) return 0
  if (!oldVersion) return 1
  let version1 = newVersion.split('.').map(item => isNaN(item) ? 0 : Number(item))
  let version2 = oldVersion.split('.').map(item => isNaN(item) ? 0 : Number(item))
  if (version1[0] > version2[0]) {
    return 1
  } else if (version1[0] < version2[0]) {
    return -1
  } else {
    if (version1[1] > version2[1]) {
      return 1
    } else if (version1[1] < version2[1]) {
      return -1
    } else {
      if (version1[2] > version2[2]) {
        return 1
      } else if (version1[2] < version2[2]) {
        return -1
      } else {
        return 0
      }
    }
  }
}